<template>
  <a-row>
    <a-card hoverable id="aCard">
      <p>
        <b>{{$t('Cluster-storage-capacity')}} 
          <span style="color: var(--themeColor);">{{ total ? total : 0 }}</span> 
        </b>
        <!-- 更多 -->
        <span class="more-text" @click="openMore">{{$t('More')}}></span>
        <!-- <img style="float: right" @click="getHistory" 暂时不用
          :src="visible ? require('../../../static/images/png/ic_history_selected.png') : require('../../../static/images/png/ic_history_normal.png')" alt=""> -->
      </p>
      <div id="cluster"></div>
    </a-card>
    <a-modal
      :title="$t('Storage_history_of_cluster')"
      :visible="visible"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
      width="45%"
      v-dragModal
    >
      <div style="text-align: right">
        <a-radio-group v-model="range" default-value="month" button-style="solid" size="small">
          <a-radio-button :value="24">
            {{$t('Day')}}
          </a-radio-button>
          <a-radio-button :value="30">
            {{$t('Month')}}
          </a-radio-button>
          <a-radio-button :value="12">
            {{$t('Year')}}
          </a-radio-button>
        </a-radio-group>
      </div>
      <div id="chartDiv" style="width: 100%;height:290px;"></div>
    </a-modal>

    <ClusterDialog :visible="cluster_dialog" @closeDrawer="closeDrawer"/>
  </a-row>
</template>
<script>
// import DataSet from "@antv/data-set";
// import {drawpie} from '../../assets/pie'
// import $ from "jquery";
import G2 from '@antv/g2'
import * as echarts from 'echarts';
import ClusterDialog from '@/components/Home/dialog/ClusterDialog'

import request from '@/request/request'

export default {
  name: "Cluster",
  components: { ClusterDialog },
  data() {
    return {
      // language:'',
      timeoutId: "",
      cludata: [
        {
          item: this.$t("Unused"),
          count: 0,
          percent: 0
        },
        {
          item: this.$t("Block"),
          count: 0,
          percent: 0
        },
        {
          item: this.$t("File-system"),
          count: 0,
          percent: 0
        },
        {
          item: this.$t("Object-storage"),
          count: 0,
          percent: 0
        }
      ],
      chart: "",
      free: '',
      total: '',
      visible: false,
      myChart: '',
      range: 30,
      option: '',
      cluster_dialog: false
      // xdata: [...Array(7)].map((k,i)=>i+1)
    };
  },
  computed:{
    getlanguage(){
      return this.$store.state.language
    }
  },
  watch:{  //因为是定时1份半重新绘图，所以得重新绘图之后才会生效
    getlanguage(val){  //监听语言切换，切换data组件内的多语言
      this.cludata= [
        {
          item: this.$t("Unused"),
          count: 0,
          percent: 0
        },
        {
          item: this.$t("Block"),
          count: 0,
          percent: 0
        },
        {
          item: this.$t("File-system"),
          count: 0,
          percent: 0
        },
        {
          item: this.$t("Object-storage"),
          count: 0,
          percent: 0
        }
      ]
      this.createNewDiv();
      this.getFree();
      this.chartdata();
    },
    range(val) {
      this.getAreaChart()
    }
  },
  mounted() {
    // drawpie(this.cludata)
    this.getFree();
    this.chartdata();
    // this.drawclu();
    this.timeoutId = setInterval(this.chartdata, 90000);
    // //再初始化之后调整图表的大小自适应
    // const e = document.createEvent("Event");
    // e.initEvent("resize", true, true);
    // window.dispatchEvent(e);
  },
  destroyed() {
    clearInterval(this.timeoutId); //清除定时器
  },
  methods: {
    //创建一个新的div，用来更换语言时，重绘画布
    createNewDiv() {
      let parentNode = document.getElementById('aCard');
      document.getElementById('cluster').remove();
      let newDiv = document.createElement("div");
      newDiv.id="cluster";
      parentNode.appendChild(newDiv);
    },
    getFree() {
      request('get', "index/store_space")
        // .get(this.allurl + "index/avail_free_space")
        .then(res => {
          if(res.data.flag == 1) {
            this.model(res.data.id) //返回模板
            this.notice(res.data.id,res.data.params,res.data.flag) //通知列表显示
          }else {
            this.free = res.data.avail_free_space;
            this.total = res.data.store_total;
            this.drawclu();
          }
        })
    },
    drawclu() {
      this.chart = new G2.Chart({
        container: "cluster",
        forceFit: true,
        height: 300,
        animate: true,
        padding: [20, 'auto', 'auto', 'auto']
      });
      this.chart.source(this.cludata, {
        percent: {
          formatter: function formatter(val) {
            val = val + "%";
            return val;
          }
        }
      });
      this.chart.coord("theta", {
        radius: 0.75,
        innerRadius: 0.6
      });
      this.chart.tooltip({
        showTitle: false,
        itemTpl:
          '<li><span style="background-color:{color};" class="g2-tooltip-marker"></span>{name}: {value}</li>'
      });
      // 辅助文本
      this.chart.guide().html({
        position: ['50%', '50%'],
        html: `<div style="text-align: center;"> <span style="color: var(--themeColor); font-weight: bold;font-size: 18px;">${this.free}</span> <br/> ${this.$t('Available-space')} </div>`,
        alignX: 'middle',
        alignY: 'middle'
      });
      this.chart
        .intervalStack()
        .position("percent")
        .color("item", ["#EBEBEB", "#2EA3E6", "#06BCAD", "#6772E5"])
        .label("percent", {
          formatter: function formatter(val, item) {
            return item.point.item + ": " + val;
          }
        })
        .tooltip("item*percent", function(item, percent) {
          percent = percent + "%";
          return {
            name: item,
            value: percent
          };
        })
        .style({
          lineWidth: 1,
          stroke: "#fff"
        });
      this.chart.render();
      // this.cludata = ''
      // interval.setSelected(data[0]);
    },
    chartdata() {
      request('get', "index/status/data")
        .then(res => {
          if(res.data.flag == 1) {
            this.model(res.data.id) //返回模板
            this.notice(res.data.id,res.data.params,res.data.flag) //通知列表显示
          }else {
            for (const clu of this.cludata) {
              if (clu.item == this.$t("Unused")) {
                clu.percent = res.data.free;
              } else if (clu.item == this.$t("Block")) {
                clu.percent = res.data.rbd;
              } else if (clu.item == this.$t("File-system")) {
                clu.percent = res.data.cephfs;
              } else if (
                clu.item == this.$t("Object-storage")
              ) {
                clu.percent = res.data.rgw;
              }
            }
            // for (var i = 0; i < this.cludata.length; i++) {
            //   if (this.cludata[i].item == this.$t("Unused")) {
            //     this.cludata[i].percent = res.data.free;
            //   } else if (this.cludata[i].item == this.$t("Block")) {
            //     this.cludata[i].percent = res.data.rbd;
            //   } else if (this.cludata[i].item == this.$t("File-system")) {
            //     this.cludata[i].percent = res.data.cephfs;
            //   } else if (
            //     this.cludata[i].item == this.$t("Object-storage")
            //   ) {
            //     this.cludata[i].percent = res.data.rgw;
            //   }
            // }
            // this.changeChartData()
            // this.drawclu()
            this.chart.changeData(this.cludata); //更新图表数据
          }
        })
        .catch(function(error) {
        });
    },
    getHistory() {
      this.visible = true
      this.$nextTick(() => {
        const chartDom = document.getElementById('chartDiv');
        this.myChart = echarts.init(chartDom);
        this.getAreaChart()
      })
    },
    handleOk() {
      this.visible = false
      this.myChart.dispose();//销毁
    },
    handleCancel() {
      this.visible = false
      this.myChart.dispose();//销毁
    },
    getAreaChart() {
      this.option = {
        // title: {
        //   text: 'Stacked Area Chart'
        // },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: [this.$t("Block"), this.$t("File-system"), this.$t("Object-storage"), this.$t("Unused")]
        },
        color: ['#2fa4e7', '#059db3', '#6772e5', '#999999'],// ,绿色, , ,
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: [...Array(this.range)].map((k,i)=>i+1)
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: this.$t("Block"),
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            emphasis: {
              focus: 'series'
            },
            data: [120, 132, 101, 134, 90, 230, 210]
          },
          {
            name: this.$t("File-system"),
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            emphasis: {
              focus: 'series'
            },
            data: [220, 182, 191, 234, 290, 330, 310]
          },
          {
            name: this.$t("Object-storage"),
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            emphasis: {
              focus: 'series'
            },
            data: [150, 232, 201, 154, 190, 330, 410]
          },
          {
            name: this.$t("Unused"),
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            emphasis: {
              focus: 'series'
            },
            data: [320, 332, 301, 334, 390, 330, 320]
          }
        ]
      };

      this.option && this.myChart.setOption(this.option);
    },

    //打开更多
    openMore() {
      this.cluster_dialog = true;
    },
    //关闭抽屉
    closeDrawer() {
      this.cluster_dialog = false;
    },
  }
};
</script>
<style scoped>
  .more-text {
    cursor: pointer;
    float: right;
    font-size: 14px;
  }
  .more-text:hover {
    color: var(--themeColor);
  }
</style>